package net.gdou.doapp.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.io.FileUtils;

/**
 * 
 * @author yuyoo
 *
 */
public class DtsLoaderImpl implements DtsLoader {
	
	private Properties props = new Properties();

	public DtsBroker getDtsBroker(String uri) { 
		
		DtsBroker broker = this.getLocaleDtsBroker(uri);
		if (null == broker) {
			broker = this.getRemoteDtsBroker(uri);
			if (null != broker) {
				this.copyRemoteSource2Locate(uri);
			}
		}
		return broker;
	}

	public DtsBroker getLocaleDtsBroker(String uri) {
		
		String lp = this.parseLocateUri(uri);		
		
		File lf = new File(lp);
		if (!lf.exists()) {
			return null;
		}
		
		DtsBroker broker = new DtsBrokerImpl(lp);
		
		return broker;
	}

	public DtsBroker getRemoteDtsBroker(String uri) {

		String rp = this.parseRemoteUri(uri);	
		DtsBroker broker = new DtsBrokerImpl(rp);
		return broker;  
	}

	public void init(String configFile) {
		FileInputStream fin = null;
		try {
			fin = new FileInputStream(configFile);
			this.props.load(fin);
		} catch (Exception e) { 
			e.printStackTrace();
		} finally {
			if (null != fin) {
				try {
					fin.close();
				} catch (Exception e) { }
			}
		}
	}
	
	protected void copyRemoteSource2Locate(String uri) {
		
		String lp = this.parseLocateUri(uri);
		String rp = this.parseRemoteUri(uri);
		 
		try {
			FileUtils.copyFile(new File(rp), new File(lp));
		} catch (IOException e) {
			 
			e.printStackTrace();
		}
		
	}
	
	public String parseRemoteUri(String uri) {
		return uri;
	}
	
	public String parseLocateUri(String uri) {
		
		if (null == uri) {
			throw new IllegalArgumentException("invalid:uri, null found!");
		}
		
		StringBuilder sb = new StringBuilder(uri.length() + 20);
		sb.append(uri);
		
		int firstSplit = sb.indexOf("/");
		if (firstSplit > 0) {
			sb.delete(0, firstSplit);
			sb.insert(0, this.props.getProperty("localeCache"));
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		
		String initFile = "D:\\programCode\\f01_companyProjects\\doApp\\resources\\dtsConfig.properties";		
		DtsLoader loader = new DtsLoaderImpl();
		loader.init(initFile);
		
		String uri = "E:/xiaogang/Sensornet DTS/data/full data set/Test/Test/2008/apr/Test 20080410 001 00001.ddf";
		DtsBroker db = loader.getDtsBroker(uri);
		DtsChannel dc = db.getDtsChannel(uri);
		System.out.println(dc.propertiesMap());
		System.out.println(dc.dataList());
		
	}
}
